/*
* Blink
*
* The basic Arduino example.  Turns on an LED on for one second,
* then off for one second, and so on...  We use pin 13 because,
* depending on your Arduino board, it has either a built-in LED
* or a built-in resistor so that you need only an LED.
*
* http://www.arduino.cc/en/Tutorial/Blink
*/
#define BaslerStrobePin 2
#define StrobePin 12
int ledPin = 13;                // LED connected to digital pin 13
volatile int okToRaise = 1;
volatile int safe;
unsigned long duration;
 
 
void setup()                    // run once, when the sketch starts
{
// Serial.begin(9600);
 pinMode(BaslerStrobePin, INPUT);             // Set Request trig from camera to INPUT
 pinMode(ledPin, OUTPUT);        // sets the digital pin as output
 pinMode(11, OUTPUT);        // sets the digital pin as output
 pinMode(StrobePin, OUTPUT);     // sets the digital pin as output
 attachInterrupt(0, startoutput, RISING);
 // Set interrupts mode to normal
 TCCR2A =0;
 // Set prescaller to 32 (2us per tick)
 TCCR2B =3;
 // Set the compare A value to 150 (total of 300us)
 OCR2A = 150;
 
}
 
/* 
* Timer Interupt
* Call only if trigger input > 300us
* 16000000/32/150 = 300uS
* 300uS is the max for the LMI Led display.
*/

ISR(TIMER2_COMPA_vect)
{
  //digitalWrite(ledPin, 1-digitalRead(ledPin));
  digitalWrite(StrobePin, LOW);    // Set the output to OFF
  safe=5000;

}

/*
* Interrupt call on a rising edge of the trigger inpur
* will only turn the output pulse to ON is delay of 6%
* is respected
* will also set the timer interrupt to be call in 300us
*/
void startoutput()
{
  if (okToRaise) 
  {
   TCNT2=1;
   TIFR2 =0xFF;
   TIMSK2 |= (1<<OCIE2A); // set interrupts=enabled for the timer
   digitalWrite(StrobePin, HIGH); // Turn on the output pulse
   okToRaise =0;
  }
 
}
 
void loop()                     // run over and over again
{
  while(digitalRead(BaslerStrobePin)); 
//  while(!digitalRead(BaslerStrobePin)); 
  duration = pulseIn(BaslerStrobePin, HIGH);
    TIMSK2 &= (0<<OCIE2A); // set interrupts=disabled
//  Serial.print(duration,DEC);
//  Serial.print(",");
  digitalWrite(StrobePin, LOW);    // sets the LED off
  delayMicroseconds((16*duration)+safe);                  // make a 6% duty cycle minimum
  safe=0;
  digitalWrite(11, 1-digitalRead(11));    // sets the LED off
  okToRaise = 1;
}


